package com.smile.commons.ip;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserAgentParser {

    public static Map<String, String> parseUserAgent(String userAgent) {
        Map<String, String> result = new HashMap<>();
        result.put("os", parseOperatingSystem(userAgent));
        result.put("browser", parseBrowser(userAgent));
        return result;
    }

    private static String parseOperatingSystem(String userAgent) {
        // 匹配操作系统部分的正则表达式 (修复了转义问题)
        Pattern osPattern = Pattern.compile("\\$(.*?)\\$");  // 正确转义了 $
        Matcher matcher = osPattern.matcher(userAgent);

        if (matcher.find()) {
            String osInfo = matcher.group(1).toLowerCase();

            // 检测并解析常见的操作系统
            if (osInfo.contains("mac os x")) {
                return parseMacOSVersion(osInfo);
            } else if (osInfo.contains("windows")) {
                return parseWindowsVersion(osInfo);
            } else if (osInfo.contains("linux")) {
                return "Linux";
            } else if (osInfo.contains("android")) {
                return "Android";
            } else if (osInfo.contains("iphone") || osInfo.contains("ipad")) {
                return "iOS";
            }
        }
        return "Unknown OS";
    }

    private static String parseMacOSVersion(String osInfo) {
        // 提取 macOS 版本号 (如 10_15_7)
        Pattern versionPattern = Pattern.compile("mac os x (\\d+_\\d+(_\\d+)?)");
        Matcher versionMatcher = versionPattern.matcher(osInfo);

        if (versionMatcher.find()) {
            // 将下划线替换为点，并格式化为更友好的版本
            return "macOS " + versionMatcher.group(1).replace('_', '.');
        }
        return "macOS";
    }

    private static String parseWindowsVersion(String osInfo) {
        // 匹配 Windows NT 版本
        Pattern ntPattern = Pattern.compile("windows nt (\\d+\\.\\d+)");
        Matcher ntMatcher = ntPattern.matcher(osInfo);

        if (ntMatcher.find()) {
            String ntVersion = ntMatcher.group(1);
            // 将 NT 版本映射为常见名称
            switch (ntVersion) {
                case "10.0": return "Windows 10/11";
                case "6.3": return "Windows 8.1";
                case "6.2": return "Windows 8";
                case "6.1": return "Windows 7";
                case "6.0": return "Windows Vista";
                case "5.1": return "Windows XP";
                default: return "Windows NT " + ntVersion;
            }
        }

        // 检查其他 Windows 版本
        if (osInfo.contains("windows 98")) return "Windows 98";
        if (osInfo.contains("windows nt")) return "Windows NT";
        if (osInfo.contains("windows")) return "Windows";

        return "Unknown Windows";
    }

    private static String parseBrowser(String userAgent) {
        // 按优先级检查浏览器类型（Edge > Firefox > Chrome > Safari）
        if (userAgent.contains("edg/")) {
            return parseBrowserVersion(userAgent, "edg/", "Edge");
        } else if (userAgent.contains("firefox/")) {
            return parseBrowserVersion(userAgent, "firefox/", "Firefox");
        } else if (userAgent.contains("chrome/")) {
            return parseBrowserVersion(userAgent, "chrome/", "Chrome");
        } else if (userAgent.contains("safari/")) {
            return parseBrowserVersion(userAgent, "safari/", "Safari");
        } else if (userAgent.contains("opera/")) {
            return parseBrowserVersion(userAgent, "opera/", "Opera");
        }
        return "Unknown Browser";
    }

    private static String parseBrowserVersion(String userAgent, String key, String browserName) {
        // 查找浏览器版本号位置
        int index = userAgent.indexOf(key);
        if (index != -1) {
            int start = index + key.length();
            int end = start;

            // 提取连续的版本号字符（允许数字和点）
            while (end < userAgent.length() &&
                    (Character.isDigit(userAgent.charAt(end)) ||
                            userAgent.charAt(end) == '.')) {
                end++;
            }

            if (end > start) {
                return browserName + " " + userAgent.substring(start, end);
            }
        }
        return browserName;
    }

    public static void main(String[] args) {
        // 测试用例
        String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36";

        Map<String, String> result = parseUserAgent(userAgent);
        System.out.println("Operating System: " + result.get("os"));
        System.out.println("Browser: " + result.get("browser"));
    }
}